package com.cloudcc.boot.security;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerTypePredicate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.function.Predicate;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    private final MultiApiKeyInterceptor multiApiKeyInterceptor;

    @Value("${spring.profiles.active:}")
    private String activeProfile;

    public WebConfig(MultiApiKeyInterceptor multiApiKeyInterceptor) {
        this.multiApiKeyInterceptor = multiApiKeyInterceptor;
    }

    @Override
    public void addInterceptors(@NotNull InterceptorRegistry registry) {
        registry.addInterceptor(multiApiKeyInterceptor)
                .addPathPatterns("/**/api/**");
    }

    @Override
    public void configurePathMatch(@NotNull PathMatchConfigurer configurer) {
        if ("local".equalsIgnoreCase(activeProfile)) {
            Predicate<Class<?>> controllerPredicate = HandlerTypePredicate.forAnnotation(Controller.class, RestController.class,
                    RequestMapping.class, GetMapping.class, PostMapping.class);
            // local环境模式下，统一加前缀
            configurer.addPathPrefix("/crm", controllerPredicate);
        }
    }

}
